<!--
 * @Author: linzq
 * @Date: 2021-08-19 11:26:37
 * @LastEditors: linzq
 * @LastEditTime: 2021-11-10 10:58:15
 * @Description: 账号权限管理
-->

<template>
  <div class="base-wrap">
    <div class="content">
      <div class="base-title">账号管理</div>
      <search
        show-export
        showAdd
        :data="searchData"
        @search-reset="reset"
        @search-submit="searchSubmit"
        @add="
          () => {
            ;(dialogVisible = true), (newUser = true)
          }
        "
      />
      <com-table :columns="columns" :data="listData" :loading="loading">
        <template slot="isCancel" slot-scope="{ row }">
          <el-switch
            :disabled="row.disabled"
            v-model="row.isCancel"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="val => statusChange(val, row)"
          />
        </template>
      </com-table>
      <el-pagination
        v-if="listData.length !== 0"
        :current-page.sync="defaultParams.pageNum"
        :page-sizes="pageSizes"
        :page-size="defaultParams.pageSize"
        class="com-table-pagination"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="25%"
      @close="closeDialog('ruleForm')"
    >
      <el-form ref="ruleForm" :model="form" label-width="100px" :rules="rules">
        <el-form-item label="账号" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入账号" style="width: 95%" :disabled="form.id">
            <el-button v-if="form.id && !changePassword" slot="append" @click="changePassword = true">
              修改密码
            </el-button>
            <el-button slot="append" v-if="changePassword" @click="changePassword = false">取消</el-button>
          </el-input>
        </el-form-item>

        <template v-if="changePassword">
          <el-form-item label="原密码" prop="oldPassword">
            <el-input v-model="form.oldPassword" type="password" placeholder="请输入账号原密码" style="width: 95%" />
          </el-form-item>
          <el-form-item label="新密码" prop="password" :error="compareTips">
            <el-input
              v-model="form.password"
              type="password"
              placeholder="请输入账号新密码"
              style="width: 95%"
              @blur="comparePassword"
            />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="form.confirmPassword"
              type="password"
              placeholder="请再次输入账号密码"
              style="width: 95%"
            />
          </el-form-item>
        </template>
        <template v-if="newUser">
          <el-form-item label="密码" prop="password">
            <el-input v-model="form.password" type="password" placeholder="请输入账号密码" style="width: 95%" />
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="form.confirmPassword"
              type="password"
              placeholder="请再次输入账号密码"
              style="width: 95%"
            />
          </el-form-item>
        </template>

        <el-form-item label="邮箱地址" prop="mailbox">
          <el-input v-if="changeMail" v-model="form.mailbox" placeholder="请输入账号邮箱" style="width: 95%" disabled>
            <el-button v-if="form.id" slot="append" @click="changeMail = false">修改邮箱地址</el-button>
          </el-input>
          <el-input v-else v-model="form.mailbox" placeholder="请输入账号邮箱" style="width: 95%" @focus="getCountDown">
            <el-button slot="append" :style="{ 'margin-right': form.id ? 0 : 'none' }" @click="getEmailCode">{{
              countDown ? `${countDown}秒后再获取` : '获取验证码'
            }}</el-button>
            <template v-if="form.id">
              <span slot="append">|</span>
              <el-button slot="append" style="margin-left: 0" @click="changeMail = true">取消</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item v-if="!changeMail" label="验证码" prop="code">
          <el-input v-model="form.code" placeholder="请输入账号邮箱" style="width: 95%" />
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch v-model="form.isCancel"></el-switch>
        </el-form-item>
        <el-form-item label="权限" prop="powerTree">
          <select-tree
            style="width: 95%"
            v-model="form.powerTree"
            :options="routeTree"
            :select-last-level="true"
            showCheckbox
            :default-props="defaultProps"
            showSearch
            :accordion="true"
            clearable
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import tableMixins from '@mixins/table-mixins'
import SelectTree from '@components/SelectTree'
// import { cleanObject } from '@/utils'

const crypto = require('crypto') // 引入fs模块
const required = { required: true, message: '此项为必填项！' }

export default {
  name: 'Route',
  components: { SelectTree },
  mixins: [tableMixins],
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      columns: [
        { key: 'userName', title: '账号' },
        { key: 'mailbox', title: '注册邮箱' },
        { key: 'createTime', title: '创建时间' },
        { key: 'isCancel', title: '是否启用', slot: true },
        {
          title: '操作',
          key: 'action',
          width: '200px',
          render: (h, params, index) => {
            return h('div', [
              !params.disabled &&
                h('el-button', {
                  props: {
                    icon: 'el-icon-edit',
                    type: 'primary',
                    size: 'mini',
                    circle: true
                  },
                  attrs: { title: '编辑' },
                  on: {
                    click: () => {
                      this.dialogTitle = '修改信息'
                      this.getDet(params.id)
                    }
                  }
                })
            ])
          }
        }
      ],
      searchData: [
        {
          type: 'input',
          field: 'userName',
          label: '账号',
          placeholder: '请输入账号',
          clearable: true
        },
        {
          type: 'select',
          field: 'isCancel',
          label: '是否启用',
          placeholder: '请选择状态名称',
          clearable: true,
          options: [
            { label: '全部', value: '' },
            { label: '是', value: '1' },
            { label: '否', value: '0' }
          ]
        }
      ],
      dialogVisible: false,
      dialogTitle: '新增账号',
      form: {
        isCancel: true,
        powerTree: [10100]
      },
      rules: {
        userName: required,
        password: required,
        oldPassword: required,
        confirmPassword: [required, { validator: validatePass }],
        mailbox: [
          required,
          {
            pattern: /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
            message: '请填写正确的邮箱地址'
          }
        ],
        code: required,
        powerTree: required
      },
      defaultProps: {
        children: 'children',
        label: 'name',
        disabled: (data, node) => {
          return !data.status
        },
        value: 'id'
      },
      routeTree: [], // 路由树
      countDown: '',
      loop: '', // 倒计时循环
      changeMail: false, // 修改邮箱地址
      changePassword: false, // 修改密码
      compareTips: '', // 对比新旧密码结果提示
      newUser: false // 新增用户
    }
  },
  filters: {},
  // 监听属性 类似于data概念
  computed: {},
  watch: {},
  created() {},
  mounted() {
    this.init()
  },
  // 方法集合
  methods: {
    // 新增弹窗关闭
    closeDialog(formName) {
      this.dialogVisible = false
      this.changePassword = false
      this.changeMail = false
      this.dialogTitle = '新增账号'
      this.newUser = false
      this.form = {
        isCancel: true,
        powerTree: [10100]
      }
      this.countDown = ''
      this.$refs[formName].resetFields()
      clearInterval(this.loop)
      this.getList()
    },
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          let str = this.form.powerTree[0]
          for (let index = 1; index < this.form.powerTree.length; index++) {
            str += ',' + this.form.powerTree[index]
          }
          const hmac = crypto.createHmac('sha256', this.form.userName)
          if (this.form.password) hmac.update(this.form.password)

          const formData = {
            isCancel: this.form.isCancel,
            userName: this.form.userName,
            password: hmac.digest('hex') || undefined,
            mailbox: this.form.mailbox,
            code: this.form.code,
            power: str
          }
          let res = false
          if (this.dialogTitle === '新增账号') {
            // 修改新增同一个接口
            res = await this.$api.account.register(formData)
            if (res) {
              this.dialogVisible = false
              this.$message.success('新增成功')
            }
          } else {
            formData.id = this.form.id
            res = await this.$api.account.update(formData)
            if (res) {
              this.dialogVisible = false
              this.$message.success('修改成功')
            }
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 账号启禁用
    async statusChange(value, row) {
      const res = await this.$api.account.update(row)
      this.getList()
    },
    async getCountDown() {
      const res = await this.$api.account.getCountDown()
      if (res) {
        this.countDown = res
        this.setCountDown()
      }
    },
    // 获取邮箱验证码
    async getEmailCode() {
      if (!this.countDown) {
        const pattern = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
        if (pattern.test(this.form.mailbox)) {
          const res = await this.$api.account.getEmailCode({ email: this.form.mailbox })
          if (res) {
            this.countDown = 60
            this.$message.success('验证码已发送！')
            // 倒计时
            this.setCountDown()
          }
        } else {
          this.$message.error('请输入正确的邮箱地址')
        }
      }
    },
    // 账号详情
    async getDet(id) {
      const res = await this.$api.account.det({ id })
      this.form = res.list[0]
      this.form.powerTree = res.list[0].power
      this.dialogVisible = true
      this.changeMail = true
    },
    // 对比新旧密码
    async comparePassword() {
      if (!this.form.password) return
      this.compareTips = ''
      const hmac = crypto.createHmac('sha256', this.form.userName)
      hmac.update(this.form.password)
      const password = hmac.digest('hex')
      const res = await this.$api.account.comparePassword({ password, id: this.form.id })
      if (!res) this.compareTips = '新旧密码不能相同'
    },
    async init() {
      const res = await this.$api.account.routeList()
      this.routeTree = res.list
      this.setCountDown()
    },

    // 倒计时方法
    setCountDown() {
      clearInterval(this.loop)
      this.loop = setInterval(() => {
        if (this.countDown == 0) {
          this.countDown = ''
          clearInterval(this.loop)
        } else {
          this.countDown--
        }
      }, 1000)
    }
  }
}
</script>
<style lang="less" scoped>
// @import url();
</style>
